<?php
namespace app\common\client;

use think\facade\Config;
use app\common\request\Curl;
use think\facade\Log;

class IotCloudClient {
    
    protected $userName = '';                                     //用户名
    protected $ip = '';                                                  //请求的ip
    protected $timeStamp = 0;                                  //请求的毫秒时间戳
    protected $key = '';                                              //系统id对应的密钥
    protected $sign = '';                                            //签名
    protected $seqId = '';                                       //请求id（唯一值）
    protected $httpHeaders = [];      //请求头
    
    /**
     * @function    构造方法
     * @param null
     * @return object
     */
    public function __construct()
    {
        $this->init();
    }
    
    
    /**
     * @function 初始化
     * @param $user_name
     * @param $key
     * @return null
     */
    private function init()
    {
        $this->ip = Config::get('iot.ip');
        $this->userName = Config::get('iot.userName');
        $this->key = Config::get('iot.password');
        $this->timeStamp = time() * 1000;
        $this->seqId = $this->createSeqId();
        $this->sign = $this->createSign();
        $this->httpHeaders = $this->headers();
    }
    
    /**
     * @function    获取车机数据
     * @param       车架号     //  LNBSCB3F2HW193212,LNBSCB3F2HW193213
     */
    public function getCarsInfo(String $vin){
        $data = http_build_query(['car_unique_id'=>$vin]);
        return $this->post('/car/getRtInfo', $data);
    }
    
    
    /**
     * @function 车辆绑定
     * @param    
     */
    public function band(String $vin,String $deviceName,String $carSn){
        $data = [];
        $data['supplierNo'] = 1376920002;
        $data['carUniqueId'] = $vin;
        $data['machineNum'] = $deviceName;
        $data['deviceName'] = $deviceName;
        $data['licensePlate'] = $carSn;
        return $this->post('/car/bindCar', $data);
    }
    
    /**
     * @function 解绑车辆
     * @param
     */
    public function unBand(String $car_unique_id){
        $data = [];
        $data['carUniqueId'] = $car_unique_id;
        $data['supplierNo'] = 1376920002;
        return $this->post('/car/unbindCar', $data);
    }
    
    /**
     * @function 控车(开锁,落锁,点火,熄火,鸣笛)
     * @param
     */
    public function operate(String $vin,String $action,int $status){
        $data = [];
        $data['car_unique_id'] = $vin;
        $data['seq_id'] = md5(time());
        $data['command'] = $action;
        $data['action'] = $status;
        $data['time'] = time()*1000;
        return $this->post('/command/doCommandAction', $data);
    }
    
    /**
     * @function 控制车辆(分时用车,长租用车,永久锁定)
     * @param
     */
    public function handleCars(String $vin,int $type){
        $data = [];
        $data['car_unique_id'] = $vin;
        $data['type'] = $type;
        return $this->post('/command/doNotifyRentType', $data);
    }
    
    /**
     * @function 拍照
     * @param
     */
    public function photographer(String $vin){
        $data = [];
        $data['car_unique_id'] = $vin;
        $data['seq_id'] = md5(time());
        $data['time'] = time()*1000;
        return $this->post('/command/doTakePhoto', $data);
    }
    
    /**
      * 历史数据
     * @param String $vin
     * @param int $timeStart
     * @param int $timeEnd
     * @return boolean|mixed
     */
    public function previous(String $vin, int $timeStart, int $timeEnd){
        $data = [];
        $data['time_start'] = $timeStart;
        $data['time_end'] = $timeEnd;
        $data['car_unique_id'] = $vin;
        return $this->post('/car/getHisInfo', $data);
    }
    
    /**
     * 车机升级
     * @param String $vin
     * @param String $version
     * @return boolean|mixed
     */
    public function upgrade(String $vin,String $version){
        $data = [];
        $data['car_unique_id'] = $vin;
        $data['version'] = $version;
        return $this->post('/machineSoftware/upgradeDevice', $data);
    }
    
    /**
     * 车型切换
     * @param String $vin
     * @param String $type
     * @return boolean|mixed
     */
    public function RentType(String $vin,String $type) {
        $data = [];
        $data['car_unique_id'] = $vin;
        $data['type'] = $type;
        return $this->post('/command/doNotifyRentType', $data);
    }
    
    /**
     * 设备注册
     * @param String $deviceName
     * @return boolean|mixed
     */
    public function registerDevice(String $deviceName){
        $data = [];
        $data['device_name'] = $deviceName;
        return $this->post('/device/registDevice', $data);
    }
    
    /**
     * 查询设备信息
     * @param String $deviceName
     * @return boolean|mixed
     */
    public function queryDetails(String $deviceName){
        $data = [];
        $data['device_name'] = $deviceName;
        return $this->post('/device/queryDeviceDetail', $data);
    }
    
    /**
     * @function    post方法
     * @param $url
     * @param $data
     */
    public function post($path,$data)
    {
        
        $url = Config::get('iot.url').$path;
        $curl = new Curl;
        $curl->set('CURLOPT_HTTPHEADER',$this->httpHeaders)->post($data)->url($url);
        
        if ($curl->error()) {
            
            Log::record('[ 请求错误 ] '.$curl->message(),'error');
            return false;
        } else {
            
            $info = $curl->info();
            
            if($info['http_code'] == 200){
                $arr = json_decode($curl->data(),true);
                if($arr !== null){
                    return $arr;
                }else{
                    Log::record('[ 解码失败 ] '.$curl->data(),'error');
                    return false;
                }               
            }else{
                Log::record('[ 请求目标 ] '.$curl->data() .$info['http_code'],'error');
                 return false;
            }
        }
    }
   
    /**
     * @function    创建请求id（不可重复）
     * @param null
     * @return string
     */
    private function createSeqId()
    {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
        .substr($charid, 0, 8).$hyphen
        .substr($charid, 8, 4).$hyphen
        .substr($charid,12, 4).$hyphen
        .substr($charid,16, 4).$hyphen
        .substr($charid,20,12)
        .chr(125);// "}"
        $uuid = str_replace(array('{','}','-'),array('','',''),$uuid);
        return $uuid;
    }
    
    /**
     * @function 生成签名
     * @param
     * @return null
     */
    private function createSign()
    {
        $string = '';                                               //第一步：对参数按照key=value的格式，并按照参数名ASCII字典序排序如下
        $string.= "user_name=".$this->userName;
        $string.= "&ip=".$this->ip;
        $string.= "&time_stamp=".$this->timeStamp;
        $string.= "&seq_id=".$this->seqId;
        $string.= "&key=".$this->key;                             //第二步：拼接API密钥
        return strtoupper(md5($string));                           //第三部：md5加密，并转化为大写
    }
    
    
    /**
     * @function    创建请求头信息
     * @param $system_name
     */
    private function headers()
    {
        $headers = [];
        $headers[] = 'User-Name:'.$this->userName;
        $headers[] = 'Ip:'.$this->ip;
        $headers[] = 'Time-Stamp:'.$this->timeStamp;
        $headers[] = 'Seq-Id:'.$this->seqId;
        $headers[] = 'Sign:'.$this->sign;
        return $headers;
    }
    

    
}